# coding=utf-8
import base64
import datetime
import hashlib
import json

import requests

from response_content import WRONG_PHONE_NUMBER, SEND_SMS_FAILED, SEND_SMS_EXCEPTION


class SMS(object):
    def __init__(self, phone, content_data, template_id):
        self.software_version = '2013-12-26'
        self.account_sid = "aaf98f8954383ba201543d37cd87068b"
        self.app_id = "aaf98f8954939ed5015493faaac00075"
        self.account_token = 'e6b9edce3d814e3ca9cca0938a1f6ec6'
        self.base_url = "https://app.cloopen.com:8883/"
        self.content_data = content_data
        self.template_id = template_id
        self.time_signature = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
        if isinstance(phone, list):
            self.phone = ",".join(phone)
        else:
            self.phone = phone

    def _get_signature(self):
        return hashlib.md5(
            (self.account_sid + self.account_token + self.time_signature).encode('utf-8')).hexdigest().upper()

    def _get_url(self):
        url = self.base_url + self.software_version + "/Accounts/" + self.account_sid + \
              "/SMS/TemplateSMS?sig=" + self._get_signature()
        return url

    def send(self):
        data = {
            "to": self.phone,
            "appId": self.app_id,
            "templateId": self.template_id,
            "datas": self.content_data,
        }

        print(self.time_signature)

        header = {
            "Authorization": base64.b64encode((self.account_sid + ":" + self.time_signature).encode('utf-8')),
            "Content-Type": "application/json;charset=utf-8",
            "Accept": "application/json"
        }
        try:
            res = requests.post(url=self._get_url(), data=json.dumps(data),
                                headers=header)
            result = json.loads(res.content.decode('utf-8'))
            if result["statusCode"] == "000000":
                return (True, "")
            elif result["statusCode"] == "160042":
                return (False, WRONG_PHONE_NUMBER)
            else:
                print(result)
                return (False, SEND_SMS_FAILED)
        except Exception as e:
            print(str(e))
            return (False, SEND_SMS_EXCEPTION)
